/*
 * Created on2022/6/21 10:54
 *
 * Copyright(c) YuZhou Big Data Laboratory CO.,Ltd, 2022.  All rights reserved.
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/

package org.yzbdl.lanius.core.event;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 事件上下文
 *
 * @author hs@yzbdl.ac.cn
 * @version 1.0
 * @date 2019/6/21 10:54
 */
public class EventContext {

    /**
     * 事件Map
     */
    private static Map<Class<? extends Event>, Set<EventListener>> eventMap = new ConcurrentHashMap<>();

    /**
     * 发布事件
     *
     * @param event
     */
    public static void publish(Event event) {
        Set<EventListener> listeners = eventMap.get(event.getClass());
        if (listeners != null) {
            for (EventListener listener : listeners) {
                listener.onEvent(event);
            }
        }
    }

    /**
     * 注册事件
     *
     * @param listener
     */
    public static void registEventListener(EventListener listener) {
        Class[] eventTypes = listener.getEventType();
        for (Class clazz : eventTypes) {

            Set<EventListener> listeners = eventMap.get(clazz);
            if (listeners == null) {
                listeners = new HashSet<>();
                eventMap.put(clazz, listeners);
            }

            listeners.add(listener);
        }
    }

}
